package com.kidyone.filepass;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import other.LogUtils;

public class TestUDPActivity extends AppCompatActivity {

    private final static int DATA_MSG = 0;
    private final static int IP_MSG = 1;
    private TextView mIPTv, mPortTv;
    private EditText mIPEt, mPortEt, mSendDataEt;
    private Button mSendBtn;

    private RadioGroup mUpdGroup;
    private RadioButton mServerBtn;
    private RadioButton mClientBtn;
    private EditText mReceiveDataEt;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_MSG:
                    SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
                    mReceiveDataEt.append("\n[" + format.format(new Date()) + "]" + msg.obj.toString());
                    break;
                case IP_MSG:
                    mIPTv.setText("本机IP ： " + getIpAddress());
                    mPortTv.setText("监听端口 ： " + msg.obj.toString());
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private DatagramSocket mReceiveSocket;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_udp);
        mIPTv = (TextView) findViewById(R.id.tv_ip);
        mPortTv = (TextView) findViewById(R.id.tv_port);
        mIPEt = (EditText) findViewById(R.id.et_ip);
        mPortEt = (EditText) findViewById(R.id.et_port);
        mSendDataEt = (EditText) findViewById(R.id.et_send);
        mReceiveDataEt = (EditText) findViewById(R.id.et_receive);

        mSendBtn = (Button) findViewById(R.id.btn_send);

        mUpdGroup = (RadioGroup) findViewById(R.id.radiogroup_udp);

        mServerBtn = (RadioButton) findViewById(R.id.btn_server);
        mClientBtn = (RadioButton) findViewById(R.id.btn_client);



        mUpdGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (mServerBtn.getId() == checkedId) {

                    LogUtils.i("服务端");

                    final String port = mPortEt.getText().toString();
                    sendMessage(1, port);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            receiveData(Integer.valueOf(port));
                        }
                    }).start();

                } else if (mClientBtn.getId() == checkedId) {
                    LogUtils.i("客户端");
                }
            }
        });

        mServerBtn.setChecked(true);

        mSendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendData(mIPEt.getText().toString(), Integer.valueOf(mPortEt.getText().toString()), mSendDataEt.getText().toString());
                    }
                }).start();

            }
        });


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSendSocket != null){
            mSendSocket.close();
        }

        if (mReceiveSocket != null){
            mReceiveSocket.close();
        }
    }

    private void sendMessage(int what, Object obj) {
        if (handler != null) {
            Message.obtain(handler, what, obj).sendToTarget();
        }
    }


    private DatagramSocket mSendSocket;

    private void sendData(String ip, int port, String data) {

        /*
         * 在Java UDP中单播与广播的代码是相同的,要实现具有广播功能的程序只需要使用广播地址即可, 例如：这里使用了本地的广播地址
         */

        try {

            byte[] msg = data.getBytes();

            InetAddress inetAddr = InetAddress.getByName(ip);

            //1.构造数据包
            DatagramPacket datagramPacket = new DatagramPacket(msg, msg.length, inetAddr, port);

            //2.创建数据报套接字并将其绑定到本地主机上的指定端口。
            mSendSocket = new DatagramSocket();

            //3.从此套接字发送数据报包。
            mSendSocket.send(datagramPacket);
            LogUtils.i("Client send msg complete: " + data);

        } catch (Exception e) {
            e.printStackTrace();
        }

        while (true) {

            try {
                byte[] receivebuf = new byte[1024];
                //1.构造 DatagramPacket，用来接收长度为 length 的数据包。
                DatagramPacket receivePacket = new DatagramPacket(receivebuf, receivebuf.length);

                // 接收返回数据
                mSendSocket.receive(receivePacket);

                //处理数据
                byte[] recvByte = Arrays.copyOfRange(receivePacket.getData(), 0, receivePacket.getLength());
                String receiveData = new String(recvByte);
                sendMessage(0, "返回数据:" + receiveData);
                LogUtils.i("返回数据:" + receiveData);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    private void receiveData(int port) {

        try {
            // 1.创建接受数据的数据包
            DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
            // 2.创建UPD 的 socket
            mReceiveSocket = new DatagramSocket(port);

            LogUtils.i("Server current start......");

            while (true) {
                // 3.接收数据
                mReceiveSocket.receive(receivePacket);

                // 4.处理数据
                byte[] recvByte = Arrays.copyOfRange(receivePacket.getData(), 0, receivePacket.getLength());
                String receiveData = new String(recvByte);
                sendMessage(0, "接收完成:" + receiveData);

                // 二：返回数据
                int receivePort = receivePacket.getPort();
                InetAddress inetAddress = receivePacket.getAddress();
                byte[] ipByte = getIpAddress().getBytes();
                DatagramPacket sendPacket = new DatagramPacket(ipByte, ipByte.length, inetAddress, receivePort);
                mReceiveSocket.send(sendPacket);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String getIpAddress() {
        WifiManager wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int i = wifiInfo.getIpAddress();
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                ((i >> 24) & 0xFF);
    }


}
